local ffi = require 'ffi'
local C = ffi.C

-- 测试用的 由于ffi 的稳定性未知 不推荐使用到正式环境 
local typedef = {}

typedef.int         = ffi.typeof "int*"
typedef.float       = ffi.typeof "float*"
typedef.char        = ffi.typeof "char*"
typedef.uint32_t    = ffi.typeof "uint32_t*"

local function gc(p)
    C.free(p)
end

local memory = {

    read = function(addr, vtype)
        local vtype = typedef[vtype]
        if not vtype then return end;
        if addr < 0x500 or addr > 0x7FFFFFFF then return end;
        local value
        local ptr = ffi.cast(vtype, addr)
        if ptr then 
            if vtype == 'char' then 
                value = ffi.string(ptr)
            else
                value = ptr[0]
            end
            ffi.gc(ptr, gc)
        end 
        ptr = nil 
        return value
    end,

    write = function(addr, value, vtype)
        local vtype = typedef[vtype]
        if not vtype then return end;
        if addr < 0x500 or addr > 0x7FFFFFFF then return end;
        local ptr = ffi.cast(vtype, addr)
        if ptr then 
            if vtype == 'char' then 
                ffi.copy(ptr, value, #value + 1)
            else
                ptr[0] = value
            end
            ffi.gc(ptr, gc)
        end 
        ptr = nil 
    end,
}

return memory
